<?php

/**
 * register actions.
 *
 * @package    sf_sandbox
 * @subpackage register
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 2692 2006-11-15 21:03:55Z fabien $
 */
class registerActions extends sfActions
{
    /**
     * Executes index action
     *
     */
    /**
     * Executes index action
     *
     */
    public function executeIndex()
    {
    }

    public function executeDoRegister()
    {
        $fcode = $this->getRequestParameter('userName');
        $password = $this->getRequestParameter('userpassword');

        $c = new Criteria();
        $c->add(AppUserPeer::USERNAME, $fcode);
        $exist = AppUserPeer::doSelectOne($c);

        if ($exist) {
            $this->setFlash('errorMsg', $this->getContext()->getI18N()->__("User Name already exist."));
            return $this->redirect('/register/index');
        }

        $uplineDistDB = MlmDistributorPeer::retrieveByPK($this->getRequestParameter('id', 1));
        if (!$uplineDistDB) {
            $uplineDistDB = MlmDistributorPeer::retrieveByPK(1);
        }
        //******************* upline distributor ID

        $app_user = new AppUser();
        $app_user->setUsername($fcode);
        $app_user->setKeepPassword($password);
        $app_user->setUserpassword($password);
        $app_user->setKeepPassword2($password);
        $app_user->setUserpassword2($password);
        $app_user->setUserRole(Globals::ROLE_DISTRIBUTOR);
        $app_user->setStatusCode(Globals::STATUS_PENDING);
        $app_user->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $app_user->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $app_user->save();

        // ****************************
        $mlm_distributor = new MlmDistributor();
        $mlm_distributor->setDistributorCode($fcode);
        $mlm_distributor->setUserId($app_user->getUserId());
        $mlm_distributor->setStatusCode(Globals::STATUS_PENDING);
        $mlm_distributor->setFullName($this->getRequestParameter('fullname'));
        $mlm_distributor->setNickname($fcode);
        $mlm_distributor->setIc($this->getRequestParameter('ic'));
        if ($this->getRequestParameter('country') == 'China') {
            $mlm_distributor->setCountry('China (PRC)');
        } else {
            $mlm_distributor->setCountry($this->getRequestParameter('country'));
        }
        $mlm_distributor->setAddress($this->getRequestParameter('address'));
        $mlm_distributor->setAddress2($this->getRequestParameter('address2'));
        $mlm_distributor->setCity($this->getRequestParameter('city'));
        $mlm_distributor->setState($this->getRequestParameter('state'));
        $mlm_distributor->setPostcode($this->getRequestParameter('zip'));
        $mlm_distributor->setEmail($this->getRequestParameter('email'));
        $mlm_distributor->setAlternateEmail($this->getRequestParameter('alt_email'));
        $mlm_distributor->setContact($this->getRequestParameter('contactNumber'));
        $mlm_distributor->setGender($this->getRequestParameter('gender'));
        if ($this->getRequestParameter('dob')) {
            list($d, $m, $y) = sfI18N::getDateForCulture($this->getRequestParameter('dob'), $this->getUser()->getCulture());
            $mlm_distributor->setDob("$y-$m-$d");
        }
        $mlm_distributor->setBankName($this->getRequestParameter('bankName'));
        $mlm_distributor->setBankAccNo($this->getRequestParameter('bankAccountNo'));
        $mlm_distributor->setBankHolderName($this->getRequestParameter('bankHolderName'));

        //$mlm_distributor->setMasterIbId($masterIB->getMasterIbId());
        //$mlm_distributor->setMasterIbCode($masterIB->getMasterIbCode());
        $mlm_distributor->setUplineDistId($uplineDistDB->getDistributorId());
        $mlm_distributor->setUplineDistCode($uplineDistDB->getDistributorCode());

        $mlm_distributor->setLeverage($this->getRequestParameter('leverage'));
        $mlm_distributor->setSpread($this->getRequestParameter('spread'));
        $mlm_distributor->setAccountType($this->getRequestParameter('account_type'));
        $mlm_distributor->setDepositCurrency($this->getRequestParameter('deposit_currency'));
        $mlm_distributor->setDepositAmount($this->getRequestParameter('deposit_amount'));
        $mlm_distributor->setSignName($this->getRequestParameter('sign_name'));
        $mlm_distributor->setSignDate(date("Y/m/d h:i:s A"));
        $mlm_distributor->setTermCondition($this->getRequestParameter('term_condition'));

        $mlm_distributor->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $mlm_distributor->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $mlm_distributor->save();

        $treeStructure = $uplineDistDB->getTreeStructure() . "|" . $mlm_distributor->getDistributorId() . "|";
        $treeLevel = $uplineDistDB->getTreeLevel() + 1;

        $mlm_distributor->setTreeLevel($treeLevel);
        $mlm_distributor->setTreeStructure($treeStructure);
        $mlm_distributor->save();

        $this->getUser()->setAttribute(Globals::SESSION_USERNAME, $fcode);

        /****************************/
        /*****  Send email **********/
        /****************************/
        $encryptionKey = "asfas1";
        $secretHash = "fsdvgfygfsddsag";

        $mt4request = new CMT4DataReciver;
        $mt4request->OpenConnection("173.201.253.129", "702");

        $params['array'] = array();
        $params['group'] = $mlm_distributor->getAccountType();
        $params['agent'] = null;
        $params['login'] = 0;
        $params['country'] = $mlm_distributor->getCountry();
        $params['state'] = $mlm_distributor->getState();
        $params['city'] = $mlm_distributor->getCity();
        $params['address'] = $mlm_distributor->getAddress();
        $params['name'] = $mlm_distributor->getFullName();
        $params['email'] = $mlm_distributor->getEmail();
        $params['password'] = $this->generateMt4Password();
        $params['password_investor'] = "123abc";
        $params['password_phone'] = null;
        if ($mlm_distributor->getAccountType() == "SocECN") {
            $params['leverage'] = 100;
        } else {
            $params['leverage'] = 500;
        }
        //$params['leverage'] = $this->getRequestParameter('leverage');
        $params['zipcode'] = "";
        $params['phone'] = "";
        $params['id'] = '';
        $params['comment'] = "";

        $answer = $mt4request->MakeRequest("createaccount", $params);

        $mt4request->CloseConnection();

        if ($answer['result'] != 1) {
            $this->setFlash('errorMsg', $answer["reason"]);
        }
        else
        {
            $app_user->setStatusCode(Globals::STATUS_ACTIVE);
            $app_user->save();

            $mlm_distributor->setMt4Username($answer['login']);
            $mlm_distributor->setMt4Userpassword($params['password']);
            $mlm_distributor->setMt4InvestorPassword($params['password_investor']);
            $mlm_distributor->setStatusCode(Globals::STATUS_ACTIVE);
            $mlm_distributor->save();

            $this->sendEmailForMt4($answer["login"], $params['password'], $mlm_distributor->getFullName(), $mlm_distributor->getEmail(), $mlm_distributor);
            $this->setFlash('successMsg', "Account " . $answer["login"] . " registered successfully.");
        }
        return $this->redirect('/register/index');
    }

    function generateMt4Password()
    {
        $max_digit = 9999;
        $digit = 4;

        $char = strtoupper(substr(str_shuffle('abcdefghjkmnpqrstuvwxyz'), 0, 4));

        $fcode = rand(0, $max_digit) . "";
        $fcode = str_pad($fcode, $digit, "0", STR_PAD_LEFT);

        return $char.$fcode;
    }

    function sendEmailForMt4($mt4UserName, $mt4Password, $fullName, $email)
    {
        if ($mt4UserName != "" && $mt4Password != "") {
            $subject = "Welcome to SocratesFX.com – Your Login Account Details";
        $body = "<table width='100%' cellspacing='0' cellpadding='0' border='0' bgcolor='#939393' align='center'>
	<tbody>
		<tr>
			<td style='padding:20px 0px'>
				<table width='800' cellspacing='0' cellpadding='0' border='0' align='center' style='background:white;font-family:Arial,Helvetica,sans-serif'>
					<tbody>
						<tr>
							<td colspan='2'>
								<table cellspacing='0' cellpadding='10' border='0'>
									<tbody>
										<tr>
											<td colspan='2'>
												<a target='_blank' href='http://www.socratesfx.com'><img height='25' border='0' src='http://socratesfx.com/wp-content/themes/twentyten/images/logo.png' alt='socratesfx'></a>
											</td>
										</tr>
									</tbody>
								</table>
							</td>
						</tr>

						<tr>
							<td colspan='2'>
								<table cellspacing='0' cellpadding='10' border='0'>
									<tbody>
										<tr>
											<td colspan='2'>
												<table style='background-color:rgb(246,246,246)'>
													<tbody>
														<tr>
															<td valign='top' style='padding-top:15px;padding-left:10px'>
															<font face='Arial, Verdana, sans-serif' size='3' color='#000000' style='font-size:13px;line-height:15px'>
																Dear <strong>".$fullName."</strong>,
																<br>
																<br>Thank you for signing up for a Live Account with SocratesFX.com. Your new Live Account is setup and we are pleased to provide your login details:
<br>
<br>																Login: <strong>".$mt4UserName."</strong>
<br>																Password: <strong>".$mt4Password."</strong>
<br>
<br>																With this account, you can trade on MT4 Terminal or Mobile Trader with the same login details.
<br>																To start trading, download the MT4 Terminal at <a target='_blank' href='http://dl.socratesfx.com/socratesfxmt4setup.exe'>here</a>.
<br>
<br>																To trade on the move, download the MT4 app from the respective app stores onto your phone:
<br>																<a target='_blank' href='http://itunes.apple.com/en/app/metatrader-4/id496212596?mt=8'>iTunes</a>
<br>																<a target='_blank' href='https://play.google.com/store/apps/details?id=net.metaquotes.metatrader4'>Play Store</a>
<br>
<br>																If you require our banking details, please refer to <a target='_blank' href='http://socratesfx.com/clients/funding/'>banking details</a> for the available funding methods. To ensure identification of your funds, please submit the transaction slip to <a target='_blank' href='mailto:support@socratesfx.com'>support@socratesfx.com</a>.
<br>
<br>																If you need any assistance, feel free to email us at <a target='_blank' href='mailto:support@socratesfx.com'>support@socratesfx.com</a>. Wishing you a pleasant and successful trading experience.
															</font>
															</td>
														</tr>
													</tbody>
												</table>
											</td>
										</tr>
									</tbody>
								</table>
							</td>
						</tr>
						<tr>
							<td width='800' style='font-size:0;line-height:0' bgcolor='#0080C8'>
							<img src='http://secure.socratesfx.com/images/email/transparent.gif' height='1'>
							</td>
						</tr>
						<tr>
							<td width='800' style='font-size:0;line-height:0' colspan='2'>
								<img src='http://secure.socratesfx.com/images/email/transparent.gif' height='10'>
							</td>
						</tr>

						<tr>
							<td width='800' style='padding:15px 15px 0px;color:rgb(153,153,153);font-size:11px' colspan='2' align='right'>
							<font face='Arial, Verdana, sans-serif' size='3' color='#000000' style='font-size:12px;line-height:15px'>
								<em>
									<strong>Socrates Trading Limited</strong><br>
									T: +852 81700 739 (SFX)<br>
									E: support@socratesfx.com<br>
									W: www.socratesfx.com
								</em>
							</font>
							<br>
							<a href='http://socratesfx.com/' target='_blank'><img src='http://socratesfx.com/wp-content/themes/twentyten/images/logo.png' height='25' border='0'></a>
							<br>
						</tr>

						<tr>
							<td width='800' style='padding:5px 15px 20px;color:rgb(153,153,153);font-size:11px' colspan='2'>
							<p align='justify'>
								<font face='Arial, Verdana, sans-serif' size='3' color='#666666' style='font-size:10px;line-height:15px'>
									The information in this email is confidential and may be legally privileged. The contents may not be disclosed or used by anyone other than the addressee. If you are not the intended recipient, any disclosure, copying, distribution or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. Socrates Trading Limited cannot accept responsibility for the accuracy or completeness of this email as it has been transmitted over a public network. If you suspect that the email may have been intercepted or amended, please call the sender. When addressed to our clients any opinion or advice contained in this email is subject to our terms of business.
									<br><br>Risk Warning: Trading Forex and Derivatives carries a high level of risk to your capital and you should only trade with money you can afford to lose. Trading financial derivatives may not be suitable for all investors, so please ensure that you fully understand the risks involved, and seek independent advice if necessary
								</font>
							</p>
						</tr>
					</tbody>
				</table>
			</td>
		</tr>
	</tbody>
</table>";

            $sendMailService = new SendMailService();
            return $sendMailService->sendMail($email, $fullName, $subject, $body);
        }
    }
}
